package common

import (
	"Demo/ginEssential/model"
	"time"

	"github.com/dgrijalva/jwt-go"
)

// jwtkey 定义加密的密钥
var jwtkey = []byte("a_secret_creat")

// Clamis 定义Token请求权限的结构体
type Clamis struct {
	UserID uint //用户名
	jwt.StandardClaims
}

// ReleaseToken 发放Token
func ReleaseToken(user model.User) (string, error) {
	expirationTime := time.Now().Add(7 * 24 * time.Hour) // 设置token的有效期
	clamis := &Clamis{
		UserID: user.ID,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expirationTime.Unix(), //token过期时间
			IssuedAt:  time.Now().Unix(),     //token发放的时间
			Issuer:    "oceanLearn.tech",     // token的发放者
			Subject:   "user token",          // token发放的主题
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, clamis)
	tokenString, err := token.SignedString(jwtkey)
	if err != nil {
		return "", err
	}
	return tokenString, nil
}

// ParseToken 解析发放的token
func ParseToken(tokenString string) (*jwt.Token, *Clamis, error) {
	clamis := &Clamis{}
	token, err := jwt.ParseWithClaims(tokenString, clamis, func(token *jwt.Token) (i interface{}, err error) {
		return jwtkey, nil
	})
	return token, clamis, err
}
